#coding=utf-8
#Boa:FramePanel:PanelProduct

import wx

import DlgKeyword
import DlgCustomerChoice
import DlgPopupSupplier
import PanelSkuSearch

from MyListCtrl import *
from product import *
from ctrlAider import *

from wx.lib.splitter import MultiSplitterWindow

[wxID_PANELPRODUCT, wxID_PANELPRODUCTSPLITTER,
] = [wx.NewId() for _init_ctrls in range(2)]

[TypeSale,TypePurchase,TypeProAll] = [i for i in range(3)]

class PanelProduct(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELPRODUCT, name=u'PanelProduct',
              parent=prnt, pos=wx.Point(432, 0), size=wx.Size(700, 668),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(700, 634))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.splitter = wx.SplitterWindow(id=wxID_PANELPRODUCTSPLITTER,
              name=u'splitter', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(740, 600), style=wx.SP_3D)
        self.splitter.SetMinimumPaneSize(2)

    def __init__(self, parent, type, peerObj=None, bSelect=True):
        '''bSelect - 是否商品双击选择模式，购销单据选择产品时使用'''
        self._init_ctrls(parent)

        self.curType = type
        self.peerObj = peerObj
        self.bSelect = bSelect

        self.myInit()

    def myInit(self):
        if not(self.bSelect):
            self.SetSize(self.GetParent().GetClientSize())
            self.splitter.SetSize(self.GetClientSize())
            print self.GetSize()
            print self.GetClientSize()
            print self.splitter.GetSize()
            print self.splitter.GetSize()

        self.curKeywords = []
        self.curCategory = None

        self.categoryList = MyCategoryTreeCtrl(self.splitter)

        self.categoryList.Bind(wx.EVT_TREE_SEL_CHANGED,
                                self.OnTreeSelChanged)

        self.winRight = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
        self.initWinRight(self.winRight)

        self.splitter.SplitVertically(self.categoryList, self.winRight, 120)

    def initWinRight(self, parent):
        listWidth = self.splitter.GetClientSize().GetWidth() - 170
        print listWidth

        if(self.curType == TypeProAll):
            self.tKeyword = wx.StaticText(id=-1,
                  label=u'\u641c\u7d22\u6807\u7b7e\uff1a', name='tKeyword',
                  parent=parent, pos=wx.Point(5, 18), size=wx.Size(85, 16),
                  style=0)

            self.btnKeyword = wx.lib.buttons.GenButton(id=-1,
                  label=u'点击选择搜索标签', name=u'btnKeyword', parent=parent,
                  pos=wx.Point(90, 10), size=wx.Size(200, 24), style=0)
            self.btnKeyword.Bind(wx.EVT_BUTTON, self.OnBtnKeywordButton)

            self.btnRmLabel = wx.Button(id=-1,
                  label=u'清除', name=u'btnRmLabel', parent=parent,
                  pos=wx.Point(300, 10), size=wx.Size(40, 24), style=0)
            self.btnRmLabel.Bind(wx.EVT_BUTTON, self.OnBtnRmLabelButton)

            self.tKeyword.Show(False)
            self.btnKeyword.Show(False)
            self.btnRmLabel.Show(False)
            self.panelSku = PanelSkuSearch.PanelSkuSearch(parent, self)
            self.panelSku.SetSize(wx.Size(600, 100))
            self.panelSku.Move(wx.Point(5, 5))
            self.panelSku.set_category(56) # 电焊网

            self.chkShowUnused = wx.CheckBox(id=-1,
                  label=u'显示禁用', parent=parent,
                  pos=wx.Point(350, 110))
            self.chkShowUnused.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxShowUnused)

            self.chkShowOnlyInventory = wx.CheckBox(id=-1,
                  label=u'仅显示有库存', parent=parent,
                  pos=wx.Point(450, 110))
            self.chkShowOnlyInventory.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxOnlyInventory)

            self.tSearch = wx.StaticText(id=-1,
                  label=u'\u641c\u7d22\uff1a', name=u'tSearch', parent=parent,
                  pos=wx.Point(12, 115), size=wx.Size(51, 16), style=0)

            self.tcSearch = wx.TextCtrl(id=-1, name=u'tcSearch',
                  parent=parent, pos=wx.Point(76, 107), size=wx.Size(120, 26),
                  style=wx.TE_PROCESS_ENTER, value=u'')
            self.tcSearch.Bind(wx.EVT_TEXT_ENTER, self.OnTcSearchTextEnter)

            self.btnSearch = wx.Button(id=-1,
                  label=u'\u641c\u7d22', name=u'btnSearch', parent=parent,
                  pos=wx.Point(200, 107), size=wx.Size(50, 26), style=0)
            self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton)

            self.btnAddLabel = wx.Button(id=-1,
                  label=u'\u6dfb\u52a0\u5230\u6807\u7b7e',
                  name=u'btnAddLabel', parent=parent, pos=wx.Point(280, 42),
                  size=wx.Size(100, 26), style=0)
            self.btnAddLabel.Bind(wx.EVT_BUTTON, self.OnBtnAddLabelButton)

            self.proList = MyProductListCtrl(parent)
            self.proList.SetSize(wx.Size(listWidth, 375))
            self.proList.Move(wx.Point(10, 140))
            self.proList.refresh()

            if not(self.bSelect):
                pass

        else:
            self.tPeer = wx.StaticText(id=-1,
                label=u'客户名称：', name=u'tPeer',
                parent=parent, pos=wx.Point(10, 32), size=wx.Size(90, 24), style=0)

            self.tcPeerName = wx.TextCtrl(id=-1,
                  name=u'tcPeerName', parent=parent, pos=wx.Point(100, 24),
                  size=wx.Size(248, 28), style=0, value=u'')

            self.btnShowPeer = wx.Button(id=-1, label=u'+',
                  name=u'btnShowPeer', parent=parent, pos=wx.Point(348, 24),
                  size=wx.Size(24, 29), style=0)
            self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton)

            self.btnSelectPeer = wx.Button(id=-1,
                  label=u'\u67e5\u627e', name=u'btnSelectPeer', parent=parent,
                  pos=wx.Point(380, 24), size=wx.Size(80, 29), style=0)
            self.btnSelectPeer.Bind(wx.EVT_BUTTON, self.OnBtnSelectPeerButton)

            # 240801 销售明细支持sku
            self.panelSku = PanelSkuSearch.PanelSkuSearch(parent, self)
            self.panelSku.SetSize(wx.Size(600, 100))
            self.panelSku.Move(wx.Point(10, 60))
            self.panelSku.set_category(56) # 电焊网

            # 240801 垂直滑动窗口
            self.splitterWin = MultiSplitterWindow(parent, style=wx.SP_LIVE_UPDATE)

            if (self.curType == TypeSale):
                self.popupWin = DlgCustomerChoice.create(self)
                self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)

                self.proList = MyListCtrlCustProRecent(self.splitterWin)

                if (self.peerObj is not None):
                    self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
                    self.tcPeer.ChangeValue(self.peerObj.getValue(self.peerObj.COL_NAME))

                self.lcDetail = MyListCtrlProSaleDetail(self.splitterWin)

            elif (self.curType == TypePurchase):
                self.tPeer.SetLabel(u'供货商名称')
                self.popupWin = DlgPopupSupplier.create(self)
                self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)

                self.proList = MyListCtrlSupplierProRecent(self.splitterWin)
##                self.proList.SetSize(wx.Size(listWidth, 265))
##                self.proList.Move(wx.Point(10, 80))
##                self.proList.setViewProSelect()
##                self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnPurItemSelected)

                if (self.peerObj is not None):
                    self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
                    self.tcPeer.ChangeValue(self.peerObj.getValue(self.peerObj.COL_NAME))

                self.lcDetail = MyListCtrlProPurDetail(self.splitterWin)
##                self.lcPurDetail.SetSize(wx.Size(listWidth, 200))
##                self.lcPurDetail.Move(wx.Point(10, 355))
##                self.lcPurDetail.setViewProSelect()

            #self.proList.SetSize(wx.Size(listWidth, 265))
            #self.proList.Move(wx.Point(10, 65))
            self.proList.setViewProSelect()
            self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSaleItemSelected)

            #self.lcDetail.SetSize(wx.Size(listWidth, 200))
            #self.lcDetail.Move(wx.Point(10, 340))
            self.lcDetail.setViewProSelect()

            self.proList.SetMinSize(wx.Size(200, 100))
            self.splitterWin.AppendWindow(self.proList, 250)

            self.lcDetail.SetMinSize(wx.Size(200, 50))
            self.splitterWin.AppendWindow(self.lcDetail)

            self.splitterWin.Move(wx.Point(10, 170))
            # 设置大小为什么必须放在最后？放在AppendWindow之前导致sashPos参数不起作用
            self.splitterWin.SetSize(wx.Size(listWidth, 460))
            self.splitterWin.SetOrientation(wx.VERTICAL)
            self.splitterWin.SizeWindows()

        #self.proList = self.getListCtrl(parent)
        if(self.bSelect):
            self.proList.Bind(wx.EVT_LEFT_DCLICK, self.OnProListLeftDclick)

    def setViewTypeProAll(self, type):
        '''只是针对TypeProAll中的列显示起作用'''
        self.typeAll_state = type
        if (type == TypeSale):
            self.proList.setViewProSelect(self.proList.viewSale)
        elif (type == TypePurchase):
            self.proList.setViewProSelect(self.proList.viewPur)
        elif (type == TypeProAll):
            #self.proList.Unbind(wx.EVT_LEFT_DCLICK)
            self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnProAllItemSelected)
            self.SetSize(self.GetParent().GetClientSize())
            self.splitter.SetSize(self.GetParent().GetClientSize())
            self.proList.SetSize(wx.Size(1110,265))

            self.lcPurDetail = MyListCtrlProPurDetail(self.winRight)
            self.lcPurDetail.SetSize(wx.Size(550, 180))
            self.lcPurDetail.Move(wx.Point(10, 420))
            #self.lcPurDetail.setViewProSelect()

            self.lcSaleDetail = MyListCtrlProSaleDetail(self.winRight)
            self.lcSaleDetail.SetSize(wx.Size(550, 180))
            self.lcSaleDetail.Move(wx.Point(570, 420))
            #self.lcSaleDetail.setViewProSelect()

##    def getListCtrl(self, parent):
##        if (self.curType == TypeProAll):
##            lc = MyProductListCtrl(parent)
##            lc.SetSize(wx.Size(490, 475))
##            lc.Move(wx.Point(10, 80))
##            lc.refresh()
##
##        elif (self.curType == TypeSale):
##            lc = MyListCtrlCustProRecent(parent)
##            lc.SetSize(wx.Size(490, 265))
##            lc.Move(wx.Point(10, 80))
##            lc.setViewProSelect()
##            if (self.peerObj is not None):
##                lc.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
##
##            lc.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSaleItemSelected)
##
##            self.lcSaleDetail = MyListCtrlProSaleDetail(parent)
##            self.lcSaleDetail.SetSize(wx.Size(490, 200))
##            self.lcSaleDetail.Move(wx.Point(10, 355))
##            self.lcSaleDetail.setViewProSelect()
##
##        elif (self.curType == TypePurchase):
##            lc = MyListCtrlSupplierProRecent(parent)
##            lc.SetSize(wx.Size(490, 265))
##            lc.Move(wx.Point(10, 80))
##            lc.setViewProSelect()
##            if (self.peerObj is not None):
##                lc.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
##            lc.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnPurItemSelected)
##
##            self.lcPurDetail = MyListCtrlProPurDetail(parent)
##            self.lcPurDetail.SetSize(wx.Size(490, 200))
##            self.lcPurDetail.Move(wx.Point(10, 355))
##            self.lcPurDetail.setViewProSelect()
##
##        else:
##            return None
##
##        return lc

    def refreshProductList(self):
        '''根据搜索条件（类别、关键字），重设产品列表'''
        categoryIds = []
        if (self.curCategory is not None):
            categoryId = self.curCategory.getFieldVal(index=CDataCategory.COL_ID)
            categoryIds = CDataCategory.getChildId(categoryId)

        keywordIds = []
        for obj in self.curKeywords:
            keywordIds.append(obj.getFieldVal(index=CDataKeyword.COL_ID))

        #重设产品
        #if(self.curType == TypeProAll):
        self.proList.setFilter(keywordIds, categoryIds, self.m_sku)
        # else:
        #    self.proList.setFilter(keywordIds, categoryIds)

        if (self.curType == TypeProAll):
            self.proList.refresh()
        elif (self.curType == TypeSale):
            if(self.peerObj is not None):
                self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
        elif (self.curType == TypePurchase):
            if(self.peerObj is not None):
                self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})

    def appendProDetail(self, data):
        '''data - ([proId,proName,unit,cnt,price,amount], )'''
        # 注意接收端参数是二维列表
        self.GetGrandParent().appendProDetail(data)

    def setSelectObj(self, obj):
        '''设置选中客户'''
        if (obj is not None):
            #if None, we keep old value
            self.peerObj = obj

        if (self.peerObj is not None):
            name = self.peerObj.getValue(self.peerObj.COL_NAME)
            self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
        else:
            name = ''

        self.tcPeer.ChangeValue(name)


    def setCustomer(self, obj):
        '''设置选中客户'''
        self.setSelectObj(obj)

    def getSelectPeer(self):
        return self.peerObj

    def setSelectPeer(self, obj):
        self.setSelectObj(obj)

    def clearSelectPeer(self):
        self.tcPeer.ChangeValue('')
        self.proList.DeleteAllItems()
        self.lcDetail.DeleteAllItems()

    def OnBtnSelectPeerButton(self, event):
        if self.tcPeer.GetValue() == '':
            self.peerObj = None

        if (self.peerObj is not None):
            self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})


    def OnProAllItemSelected(self, event):
        '''产品列表被选择，显示产品的采购与销售历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iId).GetText())
        self.lcPurDetail.refresh({'proId':proId})
        self.lcSaleDetail.refresh({'proId':proId})


    def OnPurItemSelected(self, event):
        '''采购历史页面，产品被选择后显示产品采购历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iProId).GetText())
        self.lcDetail.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID),
                                'proId':proId})

    def OnSaleItemSelected(self, event):
        '''采购历史页面，产品被选择后显示产品采购历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iProId).GetText())
        self.lcDetail.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID),
                                'proId':proId})

    def OnBtnRmLabelButton(self, event):
        self.btnKeyword.SetLabel(u'点击选择搜索标签')
        self.curKeywords = []
        self.refreshProductList()
        # 140808 以下代码是为了触发btnKeyword刷新显示
        self.btnKeyword.SetFocus()

    def OnTreeSelChanged(self, event):
        self.curCategory = self.categoryList.getSelection()
        self.m_sku=((),())
        self.refreshProductList()
        if(True):#(self.curType == TypeProAll):
            self.panelSku.set_category(self.curCategory.getKeyVal())
        event.Skip()

    def OnBtnKeywordButton(self, event):

        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()

        dlg = DlgKeyword.create(self)
        dlg.setData(self.curKeywords)
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return

##        import DlgProLabel
##        dlg = DlgProLabel.create(self)
##        if (dlg.ShowModal() == wx.ID_CANCEL):
##            return

        self.curKeywords = dlg.keywordSel
        str = ''
        for obj in self.curKeywords:
            str += '%s  ' %obj.getFieldVal(index=CDataKeyword.COL_NAME)
        btn.SetLabel(str)
        #btn.SetSize(btn.GetBestSize())
        self.refreshProductList()

    def OnProListLeftDclick(self, event):
        '''左键双击产品列表,弹出产品数量、价格窗口'''
        import DlgProGX
##        obj = self.proList.getSelectObj()
##        if (obj == None):
##            print '[Error]unknown product: %s' %(fields)

        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return

        

        charge = 0
        memo = ''

        if (self.curType == TypeSale):
            proId,proName,unit,price = self.proList.getProSaleInfo(item)
        elif (self.curType == TypePurchase):
            proId,proName,unit,price, charge, memo = self.proList.getProSaleInfo(item)
        elif (self.curType == TypeProAll):
            proId,proName,unit,price = self.proList.getProSaleInfo(item)
            
        proObj = CDataProduct.getInstance({'id':proId})
        if (proObj.getFieldVal('onUse') == 0):
            dlg = wx.MessageDialog(self, u'商品已经禁用',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return

        if (self.curType == TypeProAll and self.typeAll_state == TypePurchase):
            charge = proObj.getValue(CDataProduct.COL_FREIGHT)

        dlg = DlgProGX.create(self.GetGrandParent())
        dlg.setData(proId=proId, unit=unit, price=price
            , charge=charge# if charge>0 else proObj.getValue(CDataProduct.COL_FREIGHT) # 销售不需要显示运费
            , memo=memo)

        if (self.curType == TypeSale):
            dlg.setInbound(False)
        elif (self.curType == TypeProAll):
            if (self.typeAll_state == TypeSale):
                dlg.setInbound(False)
            elif (self.typeAll_state == TypeProAll):
                kit.showModal(u'异常状态：TypeALL')


        if (dlg.ShowModal() == wx.ID_OK):
            data = []
            #data.append([str(proId), dlg.name, dlg.unit,
            #            str(dlg.cnt), str(dlg.price), str(dlg.cnt*dlg.price), dlg.memo, dlg.charge])
            data.append([proId, dlg.name, dlg.unit,
                         dlg.cnt, dlg.price, dlg.cnt*dlg.price, dlg.memo, dlg.charge])

            for unit,cnt in dlg.lonelyUnit.items():
                #data.append([str(proId), dlg.name, unit, str(cnt), 0.0, 0.0, '', 0.0])
                data.append([proId, dlg.name, unit, cnt, 0.0, 0.0, '', 0.0])

            self.appendProDetail(data)

    def refreshList(self, val):
        #print val
        if (val == ''):
            self.proList.refresh()
        else:
            self.proList.refreshView(val)

    def OnBtnSearchButton(self, event):
        self.refreshList(self.tcSearch.GetValue())

    def OnTcSearchTextEnter(self, event):
        self.btnSearch.SetFocus()
        self.refreshList(self.tcSearch.GetValue())

    def OnBtnAddLabelButton(self, event):
        '''把搜索内容设置为label，并关联到列表中的显示项目'''
        if (self.tcSearch.GetValue() == ''):
            dlg = wx.MessageDialog(self, u'没有设置标签',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return

        # 此处允许重复操作
        labelId = CDataKeyword.add(self.tcSearch.GetValue())
        if(labelId == -1):
            dlg = wx.MessageDialog(self, u'添加标签发生错误',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return

        for row in range(self.proList.GetItemCount()):
            proObj = self.proList.getObj(row)
            proObj.attachLabel(labelId)

        msg = u'该列表中的商品已经关联到标签<%s>，可以在搜索标签中直接选择' %self.tcSearch.GetValue()
        dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
        dlg.ShowModal()

##            obj = CDataProLabel()
##            fields = {CDataProLabel.COL_PROID:self.proList.getProId(row),
##                        CDataProLabel.COL_LABELID:labelId}
##            obj.setMulFieldVal(fields)
##            obj.insert()

    def OnBtnShowPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.popupWin.Show()
        event.Skip()

    def OnCheckBoxShowUnused(self, event):
        self.proList.setShowUnused(self.chkShowUnused.GetValue())
        self.proList.refresh()

    def OnCheckBoxOnlyInventory(self, event):
        self.proList.setShowInventory(self.chkShowOnlyInventory.GetValue())
        self.proList.refresh()

    def ChangeSkuSearch(self, sku):
        self.m_sku = sku
        print sku
        self.refreshProductList()

